from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from django.http import StreamingHttpResponse
from django.utils.encoding import escape_uri_path

from equity_admin.serializers_cashbonus import *
from equity_mall.utils.pages import MyPage
from equity_mall.utils.wash_level1 import ylx_api
from equity_mall.celery import celery_app


class CashActivityModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', )
    filter_class = CashActivityFilter

    def get_queryset(self):
        user = self.request.iser
        level = user.level
        level_id = self.request.query_params.get('level_id', None)
        customizeactivity_id = self.request.query_params.get('customizeactivity_id', None)
        if level_id:
            try:
                level_list = get_level_list(level)
                level_id = int(level_id)
                if level_id in level_list:
                    level = Level.objects.filter(id=level_id).first()
            except:
                pass
        if level.level == 0:
            queryset = CashActivity.objects.all()
        elif level.level == 1:
            queryset = CashActivity.objects.filter(level__prov_id=level.id)
        elif level.level == 2:
            queryset = CashActivity.objects.filter(level__city_id=level.id)
        elif level.level == 3:
            queryset = CashActivity.objects.filter(level__district_id=level.id)
        else:
            queryset = CashActivity.objects.filter(level__branch_id=level.id)
        if customizeactivity_id:
            queryset = queryset.exclude(customizeactivityrules__customizeactivity_id=customizeactivity_id)
        return queryset.order_by('-id')

    def get_serializer_class(self):
        if self.action == 'list':
            return CashActivityListModelSerializer
        else:
            return CashActivityRetrieveModelSerializer

    def partial_update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        activity_state = self.request.data.get('activity_state', '')
        is_max_amount_by_day = self.request.data.get('is_max_amount_by_day', '')
        is_max_amount_by_user_by_day = self.request.data.get('is_max_amount_by_user_by_day', '')
        is_max_amount_by_user = self.request.data.get('is_max_amount_by_user', '')
        is_max_amount_by_customeruser = self.request.data.get('is_max_amount_by_customeruser', '')
        max_amount_by_day = self.request.data.get('max_amount_by_day', '')
        max_amount_by_user_by_day = self.request.data.get('max_amount_by_user_by_day', '')
        max_amount_by_user = self.request.data.get('max_amount_by_user', '')
        max_amount_by_customeruser = self.request.data.get('max_amount_by_customeruser', '')
        activity_description = self.request.data.get('activity_description', '')
        available_begin_time = self.request.data.get('available_begin_time', '')
        available_end_time = self.request.data.get('available_end_time', '')
        is_need_auth = self.request.data.get('is_need_auth', '')
        is_check_identity = self.request.data.get('is_check_identity', '')
        wx_channel_id = self.request.data.get('wx_channel_id', 9)
        ali_channel_id = self.request.data.get('ali_channel_id', None)
        is_push_ylx = self.request.data.get('is_push_ylx', '')
        is_psbc_card = self.request.data.get('is_psbc_card', '')
        is_wechat = self.request.data.get('is_wechat', '')
        is_white = self.request.data.get('is_white', '')
        is_merchant = self.request.data.get('is_merchant', '')
        is_limit_white = self.request.data.get('is_limit_white', '')
        is_white_merchant = self.request.data.get('is_white_merchant', '')
        white_accout = self.request.data.get('white_accout', '')
        repeat_business_no_count = self.request.data.get('repeat_business_no_count', '')
        is_keguan = self.request.data.get('is_keguan', '')
        pushEventIds = self.request.data.get('pushEventIds', '')
        if str(is_keguan) == '1':
            if not pushEventIds:
                return Response({'error': '请上传营销事件ID'}, status=status.HTTP_400_BAD_REQUEST)
            if not instance.level.account_nine:
                return Response({'error': '活动所属机构尚未绑定9位机构号,请联系管理员处理'}, status=status.HTTP_400_BAD_REQUEST)
            instance.is_keguan = 1
            instance.pushEventIds = pushEventIds
            keguan_data = {}
            keguan_data['sourceId'] = instance.activity_id
            keguan_data['pushEventIds'] = str(pushEventIds).split('|')
            keguan_data['orgNo'] = instance.level.account_nine
            keguan_data['activityName'] = instance.name
            keguan_data['startTime'] = instance.available_begin_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            keguan_data['endTime'] = instance.available_end_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            keguan_result = ylx_api('ThirdActInfoSyncGdCrm', keguan_data)
            if keguan_result['meta']['code'] != 200:
                return Response({'error': f"同步客管系统失败,原因:{keguan_result['meta']['msg']}"}, status=status.HTTP_400_BAD_REQUEST)
            CashActivityKeguanRecords.objects.create(cashactivity_id=instance.id, operate_user_id=user.id, operate_type=1)
        elif str(is_keguan) == '0':
            instance.is_keguan = 0
            CashActivityKeguanRecords.objects.create(cashactivity_id=instance.id, operate_user_id=user.id, operate_type=2)
        if activity_state:
            if instance.activity_state == 4:
                return Response({'error': '活动已结束, 不可操作'}, status=status.HTTP_400_BAD_REQUEST)
            if str(activity_state) == '1':
                instance.activity_state = 2
                instance.save()
                return Response({'success': '开启活动成功'}, status=status.HTTP_200_OK)
            elif str(activity_state) == '2':
                instance.activity_state = 3
                instance.save()
                return Response({'success': '暂停活动成功'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '无效活动状态'}, status=status.HTTP_400_BAD_REQUEST)
        if repeat_business_no_count:
            try:
                repeat_business_no_count = int(repeat_business_no_count)
            except:
                return Response({'error': '重复商户数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
            if repeat_business_no_count < 1:
                return Response({'error': '重复商户数不能小于1'}, status=status.HTTP_400_BAD_REQUEST)
            instance.repeat_business_no_count = repeat_business_no_count
        if str(is_white_merchant) == '1':
            instance.is_white_merchant = 1
        if str(is_white_merchant) == '0':
            instance.is_white_merchant = 0
        if str(is_push_ylx) == '1':
            instance.is_push_ylx = 1
        if str(is_push_ylx) == '0':
            instance.is_push_ylx = 0
        if str(is_merchant) == '1':
            instance.is_merchant = 1
        if str(is_merchant) == '0':
            instance.is_merchant = 0
        if str(is_white) == '1':
            instance.is_white = 1
        if str(is_white) == '0':
            instance.is_white = 0
        if str(is_limit_white) == '1':
            instance.is_limit_white = 1
        if str(is_limit_white) == '0':
            instance.is_limit_white = 0
        if str(is_wechat) == '1':
            instance.is_wechat = 1
        if str(is_wechat) == '0':
            instance.is_wechat = 0
        if str(is_psbc_card) in ['0', '1']:
            instance.is_psbc_card = is_psbc_card
        if str(white_accout):
            instance.white_accout = white_accout
        if str(is_max_amount_by_day):
            instance.is_max_amount_by_day = is_max_amount_by_day
        if max_amount_by_day:
            instance.max_amount_by_day = max_amount_by_day
        if ali_channel_id:
            instance.ali_channel_id = ali_channel_id
        if str(is_max_amount_by_user_by_day):
            instance.is_max_amount_by_user_by_day = is_max_amount_by_user_by_day
        if max_amount_by_user_by_day:
            instance.max_amount_by_user_by_day = max_amount_by_user_by_day
        if str(is_max_amount_by_user):
            instance.is_max_amount_by_user = is_max_amount_by_user
        if max_amount_by_user:
            instance.max_amount_by_user = max_amount_by_user
        if str(is_max_amount_by_customeruser):
            instance.is_max_amount_by_customeruser = is_max_amount_by_customeruser
        if max_amount_by_customeruser:
            instance.max_amount_by_customeruser = max_amount_by_customeruser
        if activity_description:
            instance.activity_description = activity_description
        if available_begin_time and available_end_time:
            try:
                available_begin_time = datetime.datetime.strptime(available_begin_time, '%Y-%m-%d %H:%M:%S')
                available_end_time = datetime.datetime.strptime(available_end_time, '%Y-%m-%d %H:%M:%S')
            except:
                return Response({'error': '时间格式有误'}, status=status.HTTP_400_BAD_REQUEST)
            instance.available_begin_time = available_begin_time
            instance.available_end_time = available_end_time
            if available_end_time > datetime.datetime.now() and instance.activity_state == 4:
                try:
                    conn = pymysql.connect(host=settings.DATABASES['fnonline']['HOST'],
                                           port=settings.DATABASES['fnonline']['PORT'],
                                           database=settings.DATABASES['fnonline']['NAME'],
                                           user=settings.DATABASES['fnonline']['USER'],
                                           password=settings.DATABASES['fnonline']['PASSWORD'])
                    cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
                    sql = f'''SELECT c.*,d.u_rpbalance FROM (SELECT a.*,b.rpbalance FROM (SELECT id,activity_status,owner_id,area_id,settle_amount,order_id FROM z_platform_activity WHERE template_id="{instance.activity_id}")AS a LEFT JOIN (SELECT id,rpbalance FROM orders_arealevel)AS b ON a.area_id=b.id)AS c LEFT JOIN (SELECT id,rpbalance AS u_rpbalance FROM users_users)AS d ON c.owner_id=d.id;'''
                    cursor.execute(sql)
                    row = cursor.fetchone()
                    if row['activity_status'] == 3:
                        datetime_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        owner_id = row['owner_id']
                        order_id = row['order_id']
                        area_id = row['area_id']
                        settle_amount = row['settle_amount']
                        rpbalance = row['rpbalance']
                        u_rpbalance = row['u_rpbalance']
                        a_id = row['id']
                        if rpbalance < settle_amount:
                            return Response({'error': '余额不足抵扣,不能续期'}, status=status.HTTP_400_BAD_REQUEST)
                        sql = f'''SELECT id FROM users_users WHERE mobile="{user.mobile}";'''
                        cursor.execute(sql)
                        row = cursor.fetchone()
                        createuser_id = row['id']
                        if not createuser_id:
                            return Response({'error': '你暂无权限操作续期'}, status=status.HTTP_400_BAD_REQUEST)
                        area_balance = rpbalance - settle_amount
                        balance = u_rpbalance - settle_amount
                        sql = f'''UPDATE users_users SET rpbalance={balance} WHERE id={owner_id};'''
                        cursor.execute(sql)
                        conn.commit()
                        sql = f'''UPDATE orders_arealevel SET rpbalance={area_balance} WHERE id={area_id};'''
                        cursor.execute(sql)
                        conn.commit()
                        sql = f'''UPDATE z_platform_activity SET activity_status=1,settle_amount=0 WHERE id={a_id};'''
                        cursor.execute(sql)
                        conn.commit()
                        sql = f'''INSERT INTO recharge_wyhbalance(area_id,money,b_type,user_id,remark,source,create_time) VALUES ({area_id},{settle_amount},2,{owner_id},"活动续期",9,"{datetime_now}");'''
                        cursor.execute(sql)
                        conn.commit()
                        sql = 'SELECT LAST_INSERT_ID() AS wyh_id;'
                        cursor.execute(sql)
                        row = cursor.fetchone()
                        wyh_id = row['wyh_id']
                        number = f'O{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                        sql = f'''INSERT INTO recharge_transaction(user_id,number,source,t_type,`order`,t_money,c_money,balance,area_id,addtime) VALUES ({owner_id},"{number}",9,21,{wyh_id},{settle_amount},{-settle_amount},{area_balance},{area_id},"{datetime_now}");'''
                        cursor.execute(sql)
                        conn.commit()
                        number = f'O{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                        sql = f'''INSERT INTO recharge_transaction(user_id,number,source,t_type,`order`,t_money,c_money,balance,addtime) VALUES ({owner_id},"{number}",9,16,{order_id},{settle_amount},{-settle_amount},{balance},"{datetime_now}");'''
                        cursor.execute(sql)
                        conn.commit()
                        sql = f'''INSERT INTO orders_advance(order_id,order_state,user_id,remark,advance_time) VALUES ({order_id},2,{createuser_id},"操作续期活动{instance.activity_id},扣回余额:{settle_amount}","{datetime_now}");'''
                        cursor.execute(sql)
                        conn.commit()
                    cursor.close()
                    conn.close()
                except:
                    return Response({'error': '修改失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                instance.activity_state = 3
        if str(is_need_auth):
            instance.is_need_auth = is_need_auth
        if str(is_check_identity):
            instance.is_check_identity = is_check_identity
        try:
            instance.save()
            return Response({'success': '操作成功'}, status=status.HTTP_200_OK)
        except:
            return Response({'error': '操作失败'}, status=status.HTTP_400_BAD_REQUEST)

    def allocation_max_amount(self, request):
        user = self.request.iser
        data_array = self.request.data.get('data_array', None)
        cash_activity_id = self.request.data.get('cash_activity_id', None)
        try:
            instance = self.get_queryset().get(id=cash_activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if not data_array:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.activity_state == 4:
            return Response({'error': '已结束活动不可操作'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(data_array, list):
            return Response({'error': '参数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        level_list = get_level_list(instance.level)
        level_range = instance.level.level
        max_amount__sum = instance.cashactivitylevel_set.all().aggregate(Sum('max_amount'))['max_amount__sum']
        if max_amount__sum:
            remain_amount = instance.max_amount - max_amount__sum
        else:
            remain_amount = instance.max_amount
        if instance.activity_type in [1, 2, 3]:
            with transaction.atomic():
                # 创建事务保存点
                save_id = transaction.savepoint()
                try:
                    queryset_list = []
                    for allot in data_array:
                        if int(allot['level_id']) not in level_list:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '存在无权限机构'}, status=status.HTTP_400_BAD_REQUEST)
                        if Decimal(allot['amount']) <= 0:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '分配数量须大于0'}, status=status.HTTP_400_BAD_REQUEST)
                        if remain_amount < Decimal(allot['amount']):
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '分配数据超过活动最大数'}, status=status.HTTP_400_BAD_REQUEST)
                        cashactivitylevel_data = {}
                        cashactivitylevel_data['level_id'] = allot['level_id']
                        cashactivitylevel_data['cash_activity_id'] = instance.id
                        cashactivitylevel = CashActivityLevel.objects.filter(cash_activity_id=instance.id, level_id=allot['level_id']).first()
                        if cashactivitylevel and cashactivitylevel.max_amount != 0:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': f'{cashactivitylevel.level.name}重复配置'}, status=status.HTTP_400_BAD_REQUEST)
                        if cashactivitylevel:
                            cashactivitylevel.max_amount += Decimal(allot['amount'])
                            cashactivitylevel.remain_amount += Decimal(allot['amount'])
                            cashactivitylevel.p_max_amount += Decimal(allot['amount'])
                            cashactivitylevel.p_remain_amount += Decimal(allot['amount'])
                            cashactivitylevel.save()
                        else:
                            cashactivitylevel_data['max_amount'] = Decimal(allot['amount'])
                            cashactivitylevel_data['remain_amount'] = Decimal(allot['amount'])
                            cashactivitylevel_data['p_max_amount'] = Decimal(allot['amount'])
                            cashactivitylevel_data['p_remain_amount'] = Decimal(allot['amount'])
                            cashactivitylevel_data['is_auth'] = 1
                            cashactivitylevel, create = CashActivityLevel.objects.get_or_create(defaults=cashactivitylevel_data, cash_activity_id=instance.id, level_id=allot['level_id'])
                        remain_amount -= Decimal(allot['amount'])
                        queryset_list.append(cashactivitylevel.id)
                        try:
                            cashactivitylevelrecord_data = {}
                            cashactivitylevelrecord_data['activity_level_id'] = cashactivitylevel.id
                            cashactivitylevelrecord_data['amount'] = allot['amount']
                            cashactivitylevelrecord_data['operation_type'] = 1
                            cashactivitylevelrecord_data['remain_amount'] = cashactivitylevel.remain_amount
                            cashactivitylevelrecord_data['p_remain_amount'] = cashactivitylevel.p_remain_amount
                            cashactivitylevelrecord_data['max_amount'] = cashactivitylevel.max_amount
                            cashactivitylevelrecord_data['p_max_amount'] = cashactivitylevel.p_max_amount
                            cashactivitylevelrecord_data['user_id'] = user.id
                            cashactivitylevelrecord_data['activity_id'] = instance.id
                            cashactivitylevelrecord_data['remark'] = '超管通过后台分配'
                            CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                        except Exception as e:
                            print(e)
                            pass
                    level_level_list = []
                    queryset_list1 = []
                    for i in range(4, level_range, -1):
                        level_level_list.append(i)
                        queryset = CashActivityLevel.objects.filter(id__in=queryset_list, level__level__in=level_level_list)
                        for query in queryset:
                            query_level = query.level
                            if i == 4:
                                cashactivitylevel_level_id = query_level.parent_id
                            elif i == 3:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            elif i == 2:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent_id
                                elif query_level.level == 3:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            else:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent.parent_id
                                elif query_level.level == 3:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent_id
                                elif query_level.level == 2:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            instance1 = CashActivityLevel.objects.filter(level_id=cashactivitylevel_level_id, cash_activity_id=instance.id).first()
                            if not instance1:
                                instance1 = CashActivityLevel.objects.create(level_id=cashactivitylevel_level_id, cash_activity_id=instance.id, max_amount=0)
                            queryset_list1.append(instance1.id)
                            p_max_amount = instance1.p_max_amount + query.max_amount
                            p_remain_amount = instance1.p_remain_amount + query.remain_amount
                            instance1.p_max_amount = p_max_amount
                            instance1.p_remain_amount = p_remain_amount
                            instance1.save()
                            relation_data = {
                                "parent_id": instance1.id,
                                "child_id": query.id
                            }
                            CashActivityLevelRelation.objects.get_or_create(defaults=relation_data, parent_id=instance1.id, child_id=query.id)
                    level_level_list = []
                    for i in range(4, level_range, -1):
                        level_level_list.append(i)
                        queryset = CashActivityLevel.objects.filter(id__in=queryset_list1, level__level__in=level_level_list)
                        for query in queryset:
                            query_level = query.level
                            if i == 4:
                                cashactivitylevel_level_id = query_level.parent_id
                            elif i == 3:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            elif i == 2:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent_id
                                elif query_level.level == 3:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            else:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent.parent_id
                                elif query_level.level == 3:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent_id
                                elif query_level.level == 2:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            instance1 = CashActivityLevel.objects.filter(level_id=cashactivitylevel_level_id, cash_activity_id=instance.id).first()
                            if not instance1:
                                instance1 = CashActivityLevel.objects.create(level_id=cashactivitylevel_level_id, cash_activity_id=instance.id, max_amount=0)
                            # queryset_list1.append(instance1.id)
                            # p_max_amount = instance1.p_max_amount + query.max_amount
                            # p_remain_amount = instance1.p_remain_amount + query.remain_amount
                            # instance1.p_max_amount = p_max_amount
                            # instance1.p_remain_amount = p_remain_amount
                            # instance1.save()
                            relation_data = {
                                "parent_id": instance1.id,
                                "child_id": query.id
                            }
                            CashActivityLevelRelation.objects.get_or_create(defaults=relation_data, parent_id=instance1.id, child_id=query.id)
                except Exception as e:
                    logger.error(e)
                    transaction.savepoint_rollback(save_id)
                    return Response({'error': '分配失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                transaction.savepoint_commit(save_id)
                return Response({'success': '分配成功'}, status=status.HTTP_200_OK)
        else:
            with transaction.atomic():
                # 创建事务保存点
                save_id = transaction.savepoint()
                try:
                    queryset_list = []
                    for allot in data_array:
                        if int(allot['level_id']) not in level_list:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '存在无权限机构'}, status=status.HTTP_400_BAD_REQUEST)
                        cashactivitylevel_data = {}
                        cashactivitylevel_data['level_id'] = allot['level_id']
                        cashactivitylevel_data['cash_activity_id'] = instance.id
                        cashactivitylevel = CashActivityLevel.objects.filter(cash_activity_id=instance.id, level_id=allot['level_id']).first()
                        # if cashactivitylevel and cashactivitylevel.max_amount != 0:
                        #     transaction.savepoint_rollback(save_id)
                        #     return Response({'error': f'{cashactivitylevel.level.name}重复配置'}, status=status.HTTP_400_BAD_REQUEST)
                        if cashactivitylevel:
                            if cashactivitylevel.is_auth != 1:
                                cashactivitylevel.is_auth = 1
                                cashactivitylevel.save()
                        else:
                            cashactivitylevel_data['is_auth'] = 1
                            cashactivitylevel, create = CashActivityLevel.objects.get_or_create(defaults=cashactivitylevel_data, cash_activity_id=instance.id, level_id=allot['level_id'])
                        queryset_list.append(cashactivitylevel.id)
                    level_level_list = []
                    for i in range(4, level_range, -1):
                        level_level_list.append(i)
                        queryset = CashActivityLevel.objects.filter(id__in=queryset_list, level__level__in=level_level_list)
                        for query in queryset:
                            query_level = query.level
                            if i == 4:
                                cashactivitylevel_level_id = query_level.parent_id
                            elif i == 3:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            elif i == 2:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent_id
                                elif query_level.level == 3:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            else:
                                if query_level.level == 4:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent.parent_id
                                elif query_level.level == 3:
                                    cashactivitylevel_level_id = query_level.parent.parent.parent_id
                                elif query_level.level == 2:
                                    cashactivitylevel_level_id = query_level.parent.parent_id
                                else:
                                    cashactivitylevel_level_id = query_level.parent_id
                            instance1 = CashActivityLevel.objects.filter(level_id=cashactivitylevel_level_id, cash_activity_id=instance.id).first()
                            if not instance1:
                                instance1 = CashActivityLevel.objects.create(level_id=cashactivitylevel_level_id, cash_activity_id=instance.id, max_amount=0)
                            queryset_list.append(instance1.id)
                            relation_data = {
                                "parent_id": instance1.id,
                                "child_id": query.id
                            }
                            CashActivityLevelRelation.objects.get_or_create(defaults=relation_data, parent_id=instance1.id, child_id=query.id)
                except Exception as e:
                    logger.error(e)
                    transaction.savepoint_rollback(save_id)
                    return Response({'error': '分配失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                transaction.savepoint_commit(save_id)
                return Response({'success': '分配成功'}, status=status.HTTP_200_OK)

    def allocation_max_amount_level(self, request):
        cash_activity_id = self.request.query_params.get('cash_activity_id', None)
        search = self.request.query_params.get('search', None)
        if not cash_activity_id:
            return Response({'error': '请传活动id'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = self.get_queryset().get(id=cash_activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            max_amount__sum = instance.cashactivitylevel_set.all().aggregate(Sum('max_amount'))['max_amount__sum']
            if max_amount__sum:
                remain_amount = instance.max_amount - max_amount__sum
            else:
                remain_amount = instance.max_amount
            can_remain_amount = remain_amount
        except:
            can_remain_amount = 0
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        self.request.data['can_remain_amount'] = str(can_remain_amount)
        level = instance.level
        if level.level == 0:
            queryset = Level.objects.all().order_by('level')
        elif level.level == 1:
            queryset = Level.objects.filter(prov_id=level.id).order_by('level')
        elif level.level == 2:
            queryset = Level.objects.filter(city_id=level.id).order_by('level')
        elif level.level == 3:
            queryset = Level.objects.filter(district_id=level.id).order_by('level')
        else:
            queryset = Level.objects.filter(branch_id=level.id).order_by('level')
        queryset = queryset.exclude(cashactivitylevel__cash_activity_id=instance.id)
        if search:
            queryset = queryset.filter(Q(name__contains=search) | Q(account__contains=search))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = LevelListSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = LevelListSerializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        user = self.request.iser
        activity_type = self.request.data.get('activity_type', '')
        max_amount = self.request.data.get('max_amount', '')
        level_id = self.request.data.get('level_id', '')
        name = self.request.data.get('name', '')
        available_begin_time = self.request.data.get('available_begin_time', '')
        available_end_time = self.request.data.get('available_end_time', '')
        activity_description = self.request.data.get('activity_description', '')
        max_distributed_amount = self.request.data.get('max_distributed_amount', '')
        min_distributed_amount = self.request.data.get('min_distributed_amount', '')
        cash_activity_rule = self.request.data.get('cash_activity_rule', '')
        wx_channel_id = self.request.data.get('wx_channel_id', 9)
        ali_channel_id = self.request.data.get('ali_channel_id', 1)
        max_amount_by_day = self.request.data.get('max_amount_by_day', None)
        max_amount_by_user_by_day = self.request.data.get('max_amount_by_user_by_day', None)
        max_amount_by_user = self.request.data.get('max_amount_by_user', None)
        max_amount_by_customeruser = self.request.data.get('max_amount_by_customeruser', None)
        if not all([activity_type, max_amount, level_id, name, available_begin_time, available_end_time, activity_description]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            max_amount = Decimal(max_amount)
        except:
            return Response({'error': '活动预算值格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            level = Level.objects.get(id=level_id)
        except:
            return Response({'error': '无效层级id'}, status=status.HTTP_400_BAD_REQUEST)
        if str(activity_type) not in ['1', '2', '3', '4', '5', '6', '7', '8']:
            return Response({'error': '活动类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                cash_activity_data = {}
                cash_activity_data['max_amount'] = max_amount
                cash_activity_data['remain_amount'] = max_amount
                cash_activity_data['activity_type'] = activity_type
                cash_activity_data['name'] = name
                cash_activity_data['level_id'] = level_id
                cash_activity_data['create_time'] = datetime.datetime.now()
                cash_activity_data['available_begin_time'] = available_begin_time
                cash_activity_data['available_end_time'] = available_end_time
                cash_activity_data['create_user_id'] = user.id
                cash_activity_data['activity_description'] = activity_description
                cash_activity_data['wx_channel_id'] = wx_channel_id
                cash_activity_data['ali_channel_id'] = ali_channel_id
                cash_activity_data['is_push_ylx'] = 0
                # cash_activity_data['max_amount_by_day'] = max_amount_by_day
                # cash_activity_data['max_amount_by_user_by_day'] = max_amount_by_user_by_day
                # cash_activity_data['max_amount_by_user'] = max_amount_by_user
                # cash_activity_data['max_amount_by_customeruser'] = max_amount_by_customeruser
                cash_activity = CashActivity.objects.create(**cash_activity_data)
                activity_id = f'SUT{str(cash_activity.id).zfill(8)}'
                cash_activity.activity_id = activity_id
                cash_activity.save()
                if str(activity_type) in ['1', '4', '8']:
                    if not all([max_distributed_amount, min_distributed_amount]):
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '自定义面额活动须上传派发区间值'}, status=status.HTTP_400_BAD_REQUEST)
                    try:
                        min_distributed_amount = Decimal(min_distributed_amount)
                        max_distributed_amount = Decimal(max_distributed_amount)
                    except:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '区间值格式有误'}, status=status.HTTP_400_BAD_REQUEST)
                    if max_distributed_amount < min_distributed_amount:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '区间值格式有误'}, status=status.HTTP_400_BAD_REQUEST)
                    if min_distributed_amount < 1 or max_distributed_amount > 10000:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '区间值格式有误'}, status=status.HTTP_400_BAD_REQUEST)
                    cash_activity.max_distributed_amount = max_distributed_amount
                    cash_activity.min_distributed_amount = min_distributed_amount
                    cash_activity.save()
                elif str(activity_type) in ['2', '5']:
                    if not cash_activity_rule:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '缺少规则参数'}, status=status.HTTP_400_BAD_REQUEST)
                    # probability = Decimal(0)
                    for rule in cash_activity_rule:
                        # if probability > Decimal(max_amount):
                        #     transaction.savepoint_rollback(save_id)
                        #     return Response({'error': '配置规则超过最大派发金额'}, status=status.HTTP_400_BAD_REQUEST)
                        CashActivityRule.objects.create(amount=rule['amount'], probability=rule['probability'], cash_activity_id=cash_activity.id)
                        # probability += (Decimal(rule['amount']) * Decimal(rule['probability']).quantize(Decimal("0")))
                else:
                    if not cash_activity_rule:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '缺少规则参数'}, status=status.HTTP_400_BAD_REQUEST)
                    probability = 0
                    for rule in cash_activity_rule:
                        if probability > 100:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '规则比例超过100%'}, status=status.HTTP_400_BAD_REQUEST)
                        CashActivityRule.objects.create(amount=rule['amount'], probability=rule['probability'], cash_activity_id=cash_activity.id)
                        probability += int(Decimal(rule['probability']).quantize(Decimal("0")))
                cashactivitylevelrecord_data = {}
                cashactivitylevelrecord_data['amount'] = max_amount
                cashactivitylevelrecord_data['operation_type'] = 7
                cashactivitylevelrecord_data['activity_type'] = 2
                cashactivitylevelrecord_data['remain_amount'] = max_amount
                cashactivitylevelrecord_data['p_remain_amount'] = max_amount
                cashactivitylevelrecord_data['max_amount'] = max_amount
                cashactivitylevelrecord_data['p_max_amount'] = max_amount
                cashactivitylevelrecord_data['user_id'] = user.id
                cashactivitylevelrecord_data['remark'] = '超管新增活动'
                cashactivitylevelrecord_data['activity_id'] = cash_activity.id
                CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                transaction.savepoint_commit(save_id)
                try:
                    conn = pymysql.connect(host=settings.DATABASES['fnonline']['HOST'],
                                           port=settings.DATABASES['fnonline']['PORT'],
                                           database=settings.DATABASES['fnonline']['NAME'],
                                           user=settings.DATABASES['fnonline']['USER'],
                                           password=settings.DATABASES['fnonline']['PASSWORD'])
                    cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
                    if str(ali_channel_id) == '1':
                        ali_platform_id = 15
                    elif str(ali_channel_id) == '8':
                        ali_platform_id = 49
                    else:
                        ali_platform_id = 66
                    sql = f'''
                    INSERT INTO z_platform_activity(activity_name,activity_type,platform_type,activity_status,template_id,publish_start_time,publish_end_time,total_amount,expend_amount,settle_amount,is_bind,wx_platform_id,ali_platform_id,is_self,disposition_amount) VALUES("{name}",2,3,1,"{activity_id}","{available_begin_time}","{available_end_time}","{max_amount}","0","0",0,16,{ali_platform_id},0,"{max_amount}");
                    '''
                    cursor.execute(sql)
                    conn.commit()
                finally:
                    cursor.close()
                    conn.close()
                return Response({'success': '创建成功', 'id': cash_activity.id}, status=status.HTTP_200_OK)
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                return Response({'error': '创建失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        amount = self.request.data.get('amount', None)
        instance = self.get_object()
        if not amount:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            amount = Decimal(amount)
        except:
            return Response({'error': '请上传数值参数'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.activity_state == 4:
            return Response({'error': '已结束活动不可操作'}, status=status.HTTP_400_BAD_REQUEST)
        if amount < Decimal(0):
            max_amount__sum = instance.cashactivitylevel_set.all().aggregate(Sum('max_amount'))['max_amount__sum']
            if max_amount__sum:
                remain_amount = instance.max_amount - max_amount__sum
            else:
                remain_amount = instance.max_amount
            if -amount > remain_amount:
                return Response({'error': '活动剩余额度不足扣减'}, status=status.HTTP_400_BAD_REQUEST)
            change_amount = -amount
            operation_type = 8
            remark = '超管操作减少预算'
        else:
            change_amount = amount
            operation_type = 7
            remark = '超管操作增加预算'
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                instance_id = instance.id
                while True:
                    activity = CashActivity.objects.get(id=instance_id)
                    activity_origin_remain_amount = activity.remain_amount
                    activity_origin_max_amount = activity.max_amount
                    activity_new_remain_amount = activity_origin_remain_amount + amount
                    activity_new_max_amount = activity_origin_max_amount + amount
                    result = CashActivity.objects.filter(remain_amount=activity_origin_remain_amount, id=instance_id).update(max_amount=activity_new_max_amount, remain_amount=activity_new_remain_amount)
                    if result == 0:
                        continue
                    break
                cashactivitylevelrecord_data = {}
                cashactivitylevelrecord_data['amount'] = change_amount
                cashactivitylevelrecord_data['operation_type'] = operation_type
                cashactivitylevelrecord_data['activity_type'] = 2
                cashactivitylevelrecord_data['remain_amount'] = activity_new_remain_amount
                cashactivitylevelrecord_data['p_remain_amount'] = activity_new_remain_amount
                cashactivitylevelrecord_data['max_amount'] = activity_new_max_amount
                cashactivitylevelrecord_data['p_max_amount'] = activity_new_max_amount
                cashactivitylevelrecord_data['user_id'] = user.id
                cashactivitylevelrecord_data['remark'] = remark
                cashactivitylevelrecord_data['activity_id'] = instance_id
                CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
            except Exception as e:
                logging.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '修改失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        transaction.savepoint_commit(save_id)
        return Response({'success': '修改成功'}, status=status.HTTP_200_OK)

    def cashactivity_bind_developer(self, request):
        user = self.request.iser
        activity_id = self.request.data.get('activity_id', None)
        developer_id = self.request.data.get('developer_id', None)
        try:
            instance = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.activity_type != 8:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            developer = User.objects.get(id=developer_id)
        except:
            return Response({'error': '无效开发者id'}, status=status.HTTP_400_BAD_REQUEST)
        if developer.is_developer != 1:
            return Response({'error': '关联用户尚未成为开发者'}, status=status.HTTP_400_BAD_REQUEST)
        if developer.is_active != 1:
            return Response({'error': '关联用户状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['developer_id'] = developer_id
        data['cashactivity_id'] = activity_id
        data['create_user_id'] = user.id
        CashActivityAPIRelation.objects.get_or_create(defaults=data, developer_id=developer_id, cashactivity_id=activity_id)
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def cashactivity_unbind_developer(self, request):
        id = self.request.data.get('id', None)
        if not id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            CashActivityAPIRelation.objects.filter(id=id).delete()
            return Response({'error': '操作成功'}, status=status.HTTP_200_OK)
        except:
            return Response({'error': '操作失败'}, status=status.HTTP_400_BAD_REQUEST)

    def update_cashactivity_white_table(self, request):
        user = self.request.iser
        add_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        cashactivity_id = self.request.data.get('cashactivity_id', None)
        mobile_array = self.request.data.get('mobile_array', None)
        try:
            instance = self.get_queryset().get(id=cashactivity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            mobile_array = list(set(mobile_array))
        except:
            return Response({'error': '手机号码参数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        insert_sql = 'INSERT INTO tb_cash_activity_white_table(cashactivity_id,mobile,is_admin,add_user_id, level_id,add_time) VALUES '
        for mobile in mobile_array:
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                return Response({'error': f'{mobile}非手机号格式'}, status=status.HTTP_400_BAD_REQUEST)
            insert_sql += f'({cashactivity_id},"{mobile}",1,{user.id},{user.level_id},"{add_time}"),'
        insert_sql = insert_sql[:-1]
        insert_sql += ';'
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        try:
            delete_sql = f'DELETE FROM tb_cash_activity_white_table WHERE cashactivity_id={cashactivity_id} AND is_admin=1;'
            cursor.execute(delete_sql)
            conn.commit()
            if mobile_array:
                cursor.execute(insert_sql)
                conn.commit()
        except Exception as e:
            conn.rollback()
            cursor.close()
            conn.close()
            return Response({'error': '修改失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        cursor.close()
        conn.close()
        return Response({'success': '修改成功'}, status=status.HTTP_200_OK)

    def clear_cashactivity_white_table(self, request):
        user = self.request.iser
        cashactivity_id = self.request.data.get('cashactivity_id', None)
        try:
            instance = self.get_queryset().get(id=cashactivity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        try:
            delete_sql = f'DELETE FROM tb_cash_activity_white_table WHERE cashactivity_id={cashactivity_id} AND is_admin=1;'
            cursor.execute(delete_sql)
            conn.commit()
        except Exception as e:
            conn.rollback()
            cursor.close()
            conn.close()
            return Response({'error': '清空失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        cursor.close()
        conn.close()
        return Response({'success': '清空成功'}, status=status.HTTP_200_OK)

    def add_cashactivity_white_table(self, request):
        user = self.request.iser
        add_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        cashactivity_id = self.request.data.get('cashactivity_id', None)
        my_file = self.request.FILES.get('my_file', None)
        try:
            instance = self.get_queryset().get(id=cashactivity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        if not my_file:
            return Response({'error': '请上传excel文件'}, status=status.HTTP_400_BAD_REQUEST)
        type_excel = my_file.name.split('.')[-1]
        file_contents = my_file.read()
        if type_excel not in ['xlsx', 'xls']:
            return Response({'error': '文件格式有误, 请上传excel文件'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            wb = xlrd.open_workbook(filename=None, file_contents=file_contents)  # 关键点在于这里
        except:
            return Response({'error': '文件格式有误, 请上传excel文件'}, status=status.HTTP_400_BAD_REQUEST)
        # business_no_list = CashActivityWhiteTable.objects.filter(cashactivity_id=cashactivity_id).annotate(merged_field=Concat(F('mobile'),Value(','),F('business_no'),output_field=CharField())).values_list('merged_field', flat=True)
        business_no_list = CashActivityWhiteTable.objects.filter(cashactivity_id=cashactivity_id).values_list('mobile', flat=True)
        table = wb.sheets()[0]
        nrows = table.nrows
        if nrows > 1000:
            return Response({'error': '文件数量超过1000,请拆分多份上传'}, status=status.HTTP_400_BAD_REQUEST)
        title = table.row_values(0)
        if instance.is_white_merchant == 1:
            if '商户号' not in title:
                return Response({'error': '表格字段缺少"商户号"'}, status=status.HTTP_400_BAD_REQUEST)
            business_no_index = title.index('商户号')
        if '联系人手机号' not in title:
            return Response({'error': '表格字段缺少"联系人手机号"'}, status=status.HTTP_400_BAD_REQUEST)
        mobile_index = title.index('联系人手机号')
        insert_sql = 'INSERT INTO tb_cash_activity_white_table(cashactivity_id,mobile,is_admin,add_user_id, level_id,add_time,business_no) VALUES '
        a = 0
        for i in range(1, nrows):
            rowValues = table.row_values(i)
            mobile = str(rowValues[mobile_index]).replace('.0', '').replace(' ', '')
            if instance.is_white_merchant == 1:
                business_no = str(rowValues[business_no_index]).replace('.0', '').replace(' ', '')
            else:
                business_no = ''
            if mobile not in business_no_list:
                insert_sql += f'({cashactivity_id},"{mobile}",1,{user.id},{user.level_id},"{add_time}","{business_no}"),'
                a = 1
        insert_sql = insert_sql[:-1]
        insert_sql += ';'
        if a:
            conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                                   port=settings.DATABASES['default']['PORT'],
                                   database=settings.DATABASES['default']['NAME'],
                                   user=settings.DATABASES['default']['USER'],
                                   password=settings.DATABASES['default']['PASSWORD'])
            cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
            try:
                cursor.execute(insert_sql)
                conn.commit()
            except Exception as e:
                conn.rollback()
                cursor.close()
                conn.close()
                return Response({'error': '添加失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            cursor.close()
            conn.close()
        return Response({'success': '添加成功'}, status=status.HTTP_200_OK)
        # file_name = f'{my_file.name.replace(type_excel, "").replace(".", "")}_{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.{type_excel}'

    def cashactivity_white_table(self, request):
        cashactivity_id = self.request.data.get('cashactivity_id', None)
        try:
            instance = self.get_queryset().get(id=cashactivity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        cashactivitywhitetable_set = instance.cashactivitywhitetable_set.filter(is_admin=1).values_list('mobile', flat=True)
        return Response({'data': list(cashactivitywhitetable_set)}, status=status.HTTP_200_OK)


class CashActivityWhiteTableModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('mobile', 'business_no')
    filter_class = CashActivityWhiteTableFilter
    serializer_class = CashActivityWhiteTableModelSerializer

    def get_queryset(self):
        queryset = CashActivityWhiteTable.objects.filter()
        return queryset.order_by('-id')

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def export_cashactivitywhitetable(self, request):
        user = self.request.iser
        cashactivity_id = self.request.query_params.get('cashactivity_id', None)
        level_id = self.request.query_params.get('level_id', None)
        is_admin = self.request.query_params.get('is_admin', None)
        search = self.request.query_params.get('search', None)
        level = user.level
        if level_id:
            try:
                level_list = get_level_list(level)
                level_id = int(level_id)
                if level_id in level_list:
                    level = Level.objects.filter(id=level_id).first()
            except:
                pass
        if level.level == 0:
            condition = 'WHERE id != 0'
        elif level.level == 1:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE prov_id={level.id})'
        elif level.level == 2:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE city_id={level.id})'
        elif level.level == 3:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE district_id={level.id})'
        else:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE branch_id={level.id})'
        if search:
            condition = condition + f' AND (mobile LIKE "%{search}%" OR business_no LIKE "%{search}%")'
        if cashactivity_id:
            condition = condition + f' AND cashactivity_id in ({cashactivity_id})'
        if is_admin:
            condition = condition + f' AND is_admin in ({is_admin})'
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        try:
            sql = f'''SELECT e.*,f.nickname FROM (SELECT c.*, d.city_name,district_name,branch_name FROM (SELECT * FROM (SELECT id,mobile,is_admin,add_user_id,DATE_FORMAT(add_time,'%Y-%m-%d %H:%i:%S')AS add_time,business_no FROM tb_cash_activity_white_table {condition})AS a LEFT JOIN (SELECT wyfMerchantID,`name`AS merchant_name,managerName,managermobile,level_id FROM tb_merchant)AS b ON a.business_no=b.wyfMerchantID)AS c LEFT JOIN (SELECT id,city_name,district_name,branch_name FROM tb_u_level)AS d ON c.level_id=d.id)AS e LEFT JOIN (SELECT id,nickname FROM tb_u_user)AS f ON e.add_user_id=f.id;'''
            cursor.execute(sql)
        except:
            sql = f'''SELECT e.*,f.nickname FROM (SELECT c.*, d.city_name,district_name,branch_name FROM (SELECT * FROM (SELECT id,mobile,is_admin,add_user_id,DATE_FORMAT(add_time,'%Y-%m-%d %H:%i:%S')AS add_time,business_no FROM tb_cash_activity_white_table)AS a LEFT JOIN (SELECT wyfMerchantID,`name`AS merchant_name,managerName,managermobile,level_id FROM tb_merchant)AS b ON a.business_no=b.wyfMerchantID)AS c LEFT JOIN (SELECT id,city_name,district_name,branch_name FROM tb_u_level)AS d ON c.level_id=d.id)AS e LEFT JOIN (SELECT id,nickname FROM tb_u_user)AS f ON e.add_user_id=f.id;'''
            cursor.execute(sql)
        ziduan = ['ID', '创建人角色', '创建人', '创建时间', '白名单商户号', '白名单手机号', '商户名称', '负责人姓名', '负责人手机号', '所属市公司', '所属区县', '所属网点']
        cols = ['id', 'is_admin', 'nickname', 'add_time', 'business_no', 'mobile', 'merchant_name', 'managerName', 'managermobile', 'city_name', 'district_name', 'branch_name']
        response = StreamingHttpResponse(self.get_cashactivitywhitetable_fromat(cols, cursor, conn, ziduan))
        response['Content-Type'] = 'application/octet-stream; charset=gbk'
        response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('微邮惠礼包白名单.csv'))
        return response

    def get_cashactivitywhitetable_fromat(self, cols, cursor, conn, ziduan):
        tmp_str = ""
        # 返回文件的每一列列名
        for col in ziduan:
            tmp_str += '"%s",' % (col)
        yield tmp_str.strip(",") + "\n"
        IS_ADMIN_ENUM = {
            1: '超级管理员',
            0: '客户经理'
        }
        while True:
            tmp_str = ""
            row = cursor.fetchone()
            if row is None:
                cursor.close()
                conn.close()
                break
            for col in cols:
                if col == 'is_admin':
                    tmp_str += '"%s",' % (IS_ADMIN_ENUM[row[col]])
                else:
                    tmp_str += '"%s",' % (str(row[col]).encode('GBK', 'ignore').decode('gbk') if row[col] else '')
            yield tmp_str.strip(',') + "\n"


class CashActivityLevelModelViewSet(ModelViewSet):

    pagination_class = MyPage
    search_fields = ('level__name', )
    filter_class = CashActivityLevelFilter
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)

    def get_queryset(self):
        user = self.request.iser
        level = user.level
        level_id = self.request.query_params.get('level', None)
        sort = self.request.query_params.get('sort', '')
        # activity_id = self.request.query_params.get('activity_id', None)
        # if activity_id:
        #     try:
        #         activity = AliDiscountCoupon.objects.get(id=activity_id)
        #         max_number__sum = activity.alidiscountcouponlevel_set.all().aggregate(Sum('max_number'))['max_number__sum']
        #         if max_number__sum:
        #             remain_number = activity.max_number - max_number__sum
        #         else:
        #             remain_number = activity.max_number
        #         if '_mutable' in self.request.data.__dict__:
        #             self.request.data.__dict__['_mutable'] = True
        #         self.request.data['can_remain_number'] = str(remain_number)
        #     except:
        #         pass
        if level_id:
            try:
                level_list = get_level_list(level)
                level_id = int(level_id)
                if level_id in level_list:
                    level = Level.objects.filter(id=level_id).first()
            except:
                pass
        if level.level == 0:
            queryset = CashActivityLevel.objects.filter()
        elif level.level == 1:
            queryset = CashActivityLevel.objects.filter(level__prov_id=level.id)
        elif level.level == 2:
            queryset = CashActivityLevel.objects.filter(level__city_id=level.id)
        elif level.level == 3:
            queryset = CashActivityLevel.objects.filter(level__district_id=level.id)
        else:
            queryset = CashActivityLevel.objects.filter(level__branch_id=level.id)
        if sort == '0':
            queryset = queryset.order_by('p_max_amount', 'id')
        elif sort == '1':
            queryset = queryset.order_by('-p_max_amount', 'id')
        elif sort == '2':
            queryset = queryset.order_by('p_take_amount', 'id')
        elif sort == '3':
            queryset = queryset.order_by('-p_take_amount', 'id')
        elif sort == '4':
            queryset = queryset.order_by('p_remain_amount', 'id')
        elif sort == '5':
            queryset = queryset.order_by('-p_remain_amount', 'id')
        elif sort == '6':
            queryset = queryset.order_by(F('p_take_amount') - F('p_receive_amount'), 'id')
        elif sort == '7':
            queryset = queryset.order_by(-(F('p_take_amount') - F('p_receive_amount')), 'id')
        elif sort == '8':
            queryset = queryset.order_by('p_receive_amount', 'id')
        elif sort == '9':
            queryset = queryset.order_by('-p_receive_amount', 'id')
        else:
            queryset = queryset.order_by('level__level', 'id')
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return CashActivityLevelListModelSerializer
        else:
            return CashActivityLevelRetrieveModelSerializer

    def export_cashactivitylevel(self, obj):
        activity_id = self.request.query_params.get('activity_id', None)
        search = self.request.query_params.get('search', None)
        dimensionality = self.request.query_params.get('dimensionality', '0,1,2,3,4')
        user = self.request.iser
        if not search:
            if user.level.level == 0:
                condition = f'WHERE level IN ({dimensionality})'
            elif user.level.level == 1:
                condition = f'WHERE prov_id={user.level_id} AND level IN ({dimensionality})'
            elif user.level.level == 2:
                condition = f'WHERE city_id={user.level_id} AND level IN ({dimensionality})'
            elif user.level.level == 3:
                condition = f'WHERE district_id={user.level_id} AND level IN ({dimensionality})'
            else:
                condition = f'WHERE branch_id={user.level_id} AND level IN ({dimensionality})'
        else:
            if user.level.level == 0:
                condition = f'WHERE name LIKE "%{search}%" AND level IN ({dimensionality})'
            elif user.level.level == 1:
                condition = f'WHERE prov_id={user.level_id} AND name LIKE "%{search}%" AND level IN ({dimensionality})'
            elif user.level.level == 2:
                condition = f'WHERE city_id={user.level_id} AND name LIKE "%{search}%" AND level IN ({dimensionality})'
            elif user.level.level == 3:
                condition = f'WHERE district_id={user.level_id} AND name LIKE "%{search}%" AND level IN ({dimensionality})'
            else:
                condition = f'WHERE branch_id={user.level_id} AND name LIKE "%{search}%" AND level IN ({dimensionality})'
        if not activity_id:
            condition1 = 'WHERE'
        else:
            condition1 = f'WHERE cash_activity_id="{activity_id}" AND'
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        sql = f'''
            SELECT c.*,d.name,account,prov_name,city_name,district_name,branch_name,`level` FROM (SELECT a.*,b.activity_name FROM (SELECT id,level_id,cash_activity_id,p_max_amount,p_take_amount,p_remain_amount,(p_take_amount-p_receive_amount)AS p_unclaimed_amount,p_receive_amount,remain_amount,max_amount,receive_amount,take_amount,(take_amount-receive_amount)AS unclaimed_amount FROM tb_cash_activity_level {condition1} level_id IN (SELECT id FROM tb_u_level {condition}))AS a LEFT JOIN (SELECT id,name AS activity_name FROM tb_cash_activity)AS b ON a.cash_activity_id=b.id)AS c LEFT JOIN (SELECT id,name,account,prov_name,city_name,district_name,branch_name,`level` FROM tb_u_level)AS d ON c.level_id=d.id ORDER BY `level`;
            '''
        cursor.execute(sql)
        ziduan = ['id', '活动名称', '机构名称', '机构号', '省', '市', '区县', '网点', '活动预算', '已派发额度', '剩余预算', '待领取', '已领取', '机构分得预算', '机构已派发额度', '机构剩余可派发额度', '机构待领取额度', '机构已领取额度']
        cols = ['id', 'activity_name', 'name', 'account', 'prov_name', 'city_name', 'district_name', 'branch_name', 'p_max_amount', 'p_take_amount', 'p_remain_amount', 'p_unclaimed_amount', 'p_receive_amount', 'max_amount', 'take_amount', 'remain_amount', 'unclaimed_amount', 'receive_amount']
        response = StreamingHttpResponse(self.get_cashactivitylevel_fromat(cols, cursor, conn, ziduan))
        response['Content-Type'] = 'application/octet-stream; charset=gbk'
        response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('微信礼包机构分配明细.csv'))
        return response

    def get_cashactivitylevel_fromat(self, cols, cursor, conn, ziduan):
        tmp_str = ""
        # 返回文件的每一列列名
        for col in ziduan:
            tmp_str += '"%s",' % (col)
        yield tmp_str.strip(",") + "\n"
        while True:
            tmp_str = ""
            row = cursor.fetchone()
            if row is None:
                cursor.close()
                conn.close()
                break
            for col in cols:
                # if col == 'unclaimed_number':
                #     tmp_str += '"%s",' % (row['take_number']-row['receive_number'])
                # elif col == 'wait_number':
                #     tmp_str += '"%s",' % (row['receive_number']-row['use_number'])
                if col in ['p_max_amount', 'p_take_amount', 'p_remain_amount', 'p_unclaimed_amount', 'p_receive_amount', 'max_amount', 'take_amount', 'remain_amount', 'unclaimed_amount', 'receive_amount']:
                    tmp_str += '"%s",' % (str(row[col]).encode('GBK', 'ignore').decode('gbk') if row[col] else 0)
                else:
                    tmp_str += '"%s",' % (str(row[col]).encode('GBK', 'ignore').decode('gbk') if row[col] else '')
            yield tmp_str.strip(',') + "\n"

    def batch_update_max_amount(self, request):
        data_array = self.request.data.get('data_array', None)
        if not data_array:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(data_array, list):
            return Response({'error': '参数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()

            # 暴力回滚
            try:
                for data in data_array:
                    instance = CashActivityLevel.objects.get(id=data['id'])
                    amount = -Decimal(data['amount'])
                    if amount < 0 and instance.remain_amount < abs(amount):
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': f'{instance.id}剩余数量不足扣减'}, status=status.HTTP_400_BAD_REQUEST)
                    cash_activity = instance.cash_activity
                    instance.max_amount = instance.max_amount + amount
                    instance.remain_amount = instance.remain_amount + amount
                    instance.p_max_amount = instance.p_max_amount + amount
                    instance.p_remain_amount = instance.p_remain_amount + amount
                    instance.save()
                    cash_activity.max_amount += amount
                    cash_activity.remain_amount += amount
                    cash_activity.save()
                    relation_set = instance.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_max_amount += amount
                        parent.p_remain_amount += amount
                        parent.save()
            except Exception as e:
                logger.error(e)
                # 事务回滚
                transaction.savepoint_rollback(save_id)
                return Response({'error': '修改失败'}, status=status.HTTP_400_BAD_REQUEST)
        transaction.savepoint_commit(save_id)
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        max_amount = self.request.data.get('max_amount', None)
        try:
            max_amount = Decimal(max_amount)
        except:
            return Response({'error': '请输入整数额度'}, status=status.HTTP_400_BAD_REQUEST)
        cash_activity = instance.cash_activity
        if cash_activity.activity_type not in [1, 2, 3]:
            return Response({'error': '共享额度活动不可调整额度'}, status=status.HTTP_400_BAD_REQUEST)
        if cash_activity.activity_state == 4:
            return Response({'error': '已结束活动不可操作'}, status=status.HTTP_400_BAD_REQUEST)
        # if instance.max_amount <= 0:
        #     return Response({'error': '机构活动额度不足'}, status=status.HTTP_400_BAD_REQUEST)
        instance_id = instance.id
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                while True:
                    instance = CashActivityLevel.objects.get(id=instance_id)
                    amount = max_amount - instance.max_amount
                    if amount > 0:
                        max_amount__sum = cash_activity.cashactivitylevel_set.all().aggregate(Sum('max_amount'))['max_amount__sum']
                        if max_amount__sum:
                            remain_amount = cash_activity.max_amount - max_amount__sum
                        else:
                            remain_amount = cash_activity.max_amount
                        if remain_amount < amount:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '活动额度不足'}, status=status.HTTP_400_BAD_REQUEST)
                        operation_type = 1
                        remark = '超管通过后台分配增加'
                        amount1 = amount
                    else:
                        if instance.remain_amount < -amount:
                            return Response({'error': '机构活动额度不足'}, status=status.HTTP_400_BAD_REQUEST)
                        operation_type = 2
                        remark = '超管通过后台分配减少'
                        amount1 = -amount
                    origin_remain_amount = instance.remain_amount
                    origin_max_amount = instance.max_amount
                    origin_p_remain_amount = instance.p_remain_amount
                    origin_p_max_amount = instance.p_max_amount
                    new_remain_amount = origin_remain_amount + amount
                    new_max_amount = origin_max_amount + amount
                    new_p_remain_amount = origin_p_remain_amount + amount
                    new_p_max_amount = origin_p_max_amount + amount
                    if new_max_amount == Decimal(0):
                        is_auth = 0
                    else:
                        is_auth = 1
                    result = CashActivityLevel.objects.filter(id=instance_id, remain_amount=origin_remain_amount).update(
                        max_amount=new_max_amount,
                        remain_amount=new_remain_amount,
                        p_max_amount=new_p_max_amount,
                        p_remain_amount=new_p_remain_amount,
                        is_auth=is_auth
                    )
                    if result == 0:
                        continue
                    try:
                        cashactivitylevelrecord_data = {}
                        cashactivitylevelrecord_data['activity_level_id'] = instance.id
                        cashactivitylevelrecord_data['amount'] = amount1
                        cashactivitylevelrecord_data['operation_type'] = operation_type
                        cashactivitylevelrecord_data['remain_amount'] = new_remain_amount
                        cashactivitylevelrecord_data['p_remain_amount'] = new_p_remain_amount
                        cashactivitylevelrecord_data['max_amount'] = new_max_amount
                        cashactivitylevelrecord_data['p_max_amount'] = new_p_max_amount
                        cashactivitylevelrecord_data['user_id'] = user.id
                        cashactivitylevelrecord_data['remark'] = remark
                        CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                    except Exception as e:
                        print(e)
                        pass
                    break
                relation_set = instance.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_max_amount += amount
                    parent.p_remain_amount += amount
                    parent.save()
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '调配失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            transaction.savepoint_commit(save_id)
            return Response({'success': '调配成功'}, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.p_take_amount != 0:
            return Response({'error': '已派发额度,不可删除'}, status=status.HTTP_400_BAD_REQUEST)
        cash_activity = instance.cash_activity
        if cash_activity.activity_type in [1, 2, 3]:
            relation_set = instance.child_set.all()
            for relation in relation_set:
                parent = relation.parent
                parent.p_max_amount -= instance.max_amount
                parent.p_remain_amount -= instance.p_remain_amount
                parent.save()
                if parent.p_max_amount == Decimal(0):
                    parent.delete()
            relation_set = instance.parent_set.all()
            for relation in relation_set:
                relation.delete()
                child = relation.child
                child.delete()
        instance.delete()
        return Response({'success': '撤销成功'}, status=status.HTTP_200_OK)

    def cash_distributed_statistical(self, request):
        cash_activity_id = self.request.query_params.get('cash_activity_id', None)
        if not cash_activity_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        instance = self.get_queryset().filter(cash_activity_id=cash_activity_id).order_by('level__level').first()
        if not instance:
            return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        serializer = CashActivityLevelStatisticalModelSerializer(instance)
        return Response({"statisticsData": serializer.data, 'date_now': datetime.datetime.now().strftime('%Y年%m月%d日')}, status=status.HTTP_200_OK)

    def cashactivitylevel_tree(self, requset):
        cash_activity_id = self.request.query_params.get('cash_activity_id', None)
        if not cash_activity_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        instance = self.get_queryset().filter(cash_activity_id=cash_activity_id).order_by('level__level').first()
        if not instance:
            return Response({}, status=status.HTTP_200_OK)
        serializer = CashActivityLevelTreeModelSerializer(instance)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def cashactivitylevel_tree1(self, requset):
        cash_activity_id = self.request.query_params.get('cash_activity_id', None)
        cash_activity_level_id = self.request.query_params.get('cash_activity_level_id', None)
        if not cash_activity_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not cash_activity_level_id:
            queryset = self.get_queryset().filter(cash_activity_id=cash_activity_id).order_by('level__level')[:1]
        else:
            try:
                instance = self.get_queryset().get(id=cash_activity_level_id)
            except:
                return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
            level = instance.level
            if level.level == 1:
                queryset = self.get_queryset().filter(child_set__parent_id=instance.id, level__level=2)
            elif level.level == 2:
                queryset = self.get_queryset().filter(child_set__parent_id=instance.id, level__level=3)
            elif level.level == 3:
                queryset = self.get_queryset().filter(child_set__parent_id=instance.id, level__level=4)
            elif level.level == 0:
                queryset = self.get_queryset().filter(child_set__parent_id=instance.id, level__level=1)
            else:
                queryset = self.get_queryset().filter(level__level=5)
        # if not instance:
        #     return Response({'error': '无效活动id'}, status=status.HTTP_400_BAD_REQUEST)
        serializer = CashActivityLevelListModelSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class CashActivityDataModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_class = CashActivityDataFilter
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('customer_user__mobile', 'mobile')

    def get_queryset(self):
        user = self.request.iser
        level = user.level
        level_id = self.request.query_params.get('level', None)
        cash_activity_level_id = self.request.query_params.get('cash_activity_level_id', None)
        if level_id:
            try:
                level_list = get_level_list(level)
                level_id = int(level_id)
                if level_id in level_list:
                    level = Level.objects.filter(id=level_id).first()
            except:
                pass
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        if level.level == 0:
            queryset = CashActivityData.objects.all().order_by('-id')
        elif level.level == 1:
            queryset = CashActivityData.objects.filter(level__prov_id=level.id).order_by('-id')
        elif level.level == 2:
            queryset = CashActivityData.objects.filter(level__city_id=level.id).order_by('-id')
        elif level.level == 3:
            queryset = CashActivityData.objects.filter(level__district_id=level.id).order_by('-id')
        else:
            queryset = CashActivityData.objects.filter(level__branch_id=level.id).order_by('-id')
        if cash_activity_level_id:
            try:
                activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                self.request.data['acitivty_info'] = CashActivityLevelListModelSerializer(activity_level).data
                relation_set = list(activity_level.parent_set.all().values_list('child_id', flat=True))
                relation_set.append(cash_activity_level_id)
                queryset = queryset.filter(cash_activity_level_id__in=relation_set)
            except:
                self.request.data['acitivty_info'] = {}
            # try:
            #     cash_activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
            #     queryset = queryset.filter(cash_activity_id=cash_activity_level.cash_activity_id)
            # except:
            #     queryset = queryset.filter(cash_activity_level_id=cash_activity_level_id)
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return CashActivityDataListModelSerializer
        else:
            return CashActivityDataRetrieveModelSerializer

    def export_cashactivitydata(self, request):
        user = self.request.iser
        activity_id = self.request.query_params.get('activity_id', None)
        cash_activity_level_id = self.request.query_params.get('cash_activity_level_id', None)
        level_id = self.request.query_params.get('level_id', None)
        state = self.request.query_params.get('state', None)
        search = self.request.query_params.get('search', None)
        create_time_begin = self.request.query_params.get('create_time_begin', None)
        create_time_end = self.request.query_params.get('create_time_end', None)
        level = user.level
        if level_id:
            try:
                level_list = get_level_list(level)
                level_id = int(level_id)
                if level_id in level_list:
                    level = Level.objects.filter(id=level_id).first()
            except:
                pass
        if level.level == 0:
            condition = 'WHERE id != 0'
        elif level.level == 1:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE prov_id={level.id})'
        elif level.level == 2:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE city_id={level.id})'
        elif level.level == 3:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE district_id={level.id})'
        else:
            condition = f'WHERE level_id IN (SELECT id FROM tb_u_level WHERE branch_id={level.id})'
        if search:
            condition = condition + f' AND customer_user_id IN (SELECT id FROM tb_u_customer_user WHERE mobile LIKE "%{search}%")'
        if activity_id:
            condition = condition + f' AND cash_activity_id in ({activity_id})'
        if state:
            condition = condition + f' AND state in ({state})'
        if create_time_begin:
            condition = condition + f' AND create_time >= "{create_time_begin + " 00:00:00"}"'
        if create_time_end:
            condition = condition + f' AND create_time <= "{create_time_end + " 23:59:59"}"'
        if cash_activity_level_id:
            activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
            relation_set = list(activity_level.parent_set.all().values_list('child_id', flat=True))
            relation_set.append(cash_activity_level_id)
            if len(relation_set) == 1:
                condition = condition + f' AND cash_activity_level_id IN {str(tuple(relation_set)).replace(",", "")}'
            else:
                condition = condition + f' AND cash_activity_level_id IN {tuple(relation_set)}'

        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        try:
            cashactivity = CashActivity.objects.get(id=activity_id)
        except:
            condition = 'WHERE id=1'
            # condition = 'WHERE level_id IN (SELECT id FROM tb_u_level WHERE city_id=8846) AND state=2'
            sql = f'''
            SELECT k.*,l.mchid,mchid_name FROM (SELECT i.*,j.activity_name FROM (SELECT g.*, h.account,branch_name,city_name,district_name,account_nine FROM (SELECT e.*, f.companyuser_account,companyuser_banch FROM (SELECT c.*,d.idcode,realname,openid FROM (SELECT a.*,b.companyuser_level_id,companyuser_mobile,companyuser_name FROM (SELECT id,cash_activity_id,amount,state,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%S')AS create_time,DATE_FORMAT(received_time,'%Y-%m-%d %H:%i:%S')AS received_time,DATE_FORMAT(expired_time,'%Y-%m-%d %H:%i:%S')AS expired_time,customer_user_id,companyuser_id,payment_no,return_msg,level_id,mobile,channel_id FROM tb_cash_activity_data {condition})AS a LEFT JOIN (SELECT id,nickname AS companyuser_name,mobile AS companyuser_mobile,level_id AS companyuser_level_id FROM tb_u_user)AS b ON a.companyuser_id=b.id)AS c LEFT JOIN (SELECT id,realname,idcode,new_openid AS openid FROM tb_u_customer_user)AS d ON c.customer_user_id=d.id)AS e LEFT JOIN (SELECT id,name AS companyuser_banch,account AS companyuser_account FROM tb_u_level)AS f ON e.companyuser_level_id=f.id)AS g LEFT JOIN (SELECT id,name AS branch_name,account,city_name,district_name,account_nine FROM tb_u_level)AS h ON g.level_id=h.id)AS i LEFT JOIN (SELECT id,name AS activity_name FROM tb_cash_activity)AS j ON i.cash_activity_id=j.id)AS k LEFT JOIN (SELECT id,mchid,name AS mchid_name FROM tb_channel)AS l ON k.channel_id=l.id;
            '''
            cursor.execute(sql)
            ziduan = ['ID', '活动名称', '活动id', '所属市公司', '所属区县', '所属网点', '领取金额', '领取状态', '派发时间', '领取时间', '撤销时间', '用户openid',
                      '领取人姓名', '领取人手机号',
                      '领取人身份证', '派发员工', '派发员工手机号', '派发员工所属网点', '派发员工网点机构号', '领取渠道', '派发服务商号', '派发流水号', '失败原因', '机构号']
            cols = ['id', 'activity_name', 'cash_activity_id', 'city_name', 'district_name', 'branch_name', 'amount',
                    'state', 'create_time', 'received_time', 'expired_time', 'openid', 'realname', 'mobile', 'idcode',
                    'companyuser_name', 'companyuser_mobile', 'companyuser_banch', 'companyuser_account', 'mchid_name',
                    'mchid', 'payment_no', 'return_msg', 'account_nine']
            response = StreamingHttpResponse(self.get_cashactivitydata_fromat(cols, cursor, conn, ziduan))
            response['Content-Type'] = 'application/octet-stream; charset=gbk'
            response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('微邮惠礼包派发数据.csv'))
            return response
        if cashactivity.is_merchant == 1:
            try:
                sql = f'''
                SELECT q.*,r.merchant_level_name FROM (SELECT * FROM (SELECT * FROM (SELECT k.*,l.mchid,mchid_name FROM (SELECT i.*,j.activity_name FROM (SELECT g.*, h.account,branch_name,city_name,district_name,account_nine FROM (SELECT e.*, f.companyuser_account,companyuser_banch FROM (SELECT c.*,d.idcode,realname,openid FROM (SELECT a.*,b.companyuser_level_id,companyuser_mobile,companyuser_name FROM (SELECT id,cash_activity_id,amount,state,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%S')AS create_time,DATE_FORMAT(received_time,'%Y-%m-%d %H:%i:%S')AS received_time,DATE_FORMAT(expired_time,'%Y-%m-%d %H:%i:%S')AS expired_time,customer_user_id,companyuser_id,payment_no,return_msg,level_id,mobile,channel_id FROM tb_cash_activity_data {condition})AS a LEFT JOIN (SELECT id,nickname AS companyuser_name,mobile AS companyuser_mobile,level_id AS companyuser_level_id FROM tb_u_user)AS b ON a.companyuser_id=b.id)AS c LEFT JOIN (SELECT id,realname,idcode,new_openid AS openid FROM tb_u_customer_user)AS d ON c.customer_user_id=d.id)AS e LEFT JOIN (SELECT id,name AS companyuser_banch,account AS companyuser_account FROM tb_u_level)AS f ON e.companyuser_level_id=f.id)AS g LEFT JOIN (SELECT id,name AS branch_name,account,city_name,district_name,account_nine FROM tb_u_level)AS h ON g.level_id=h.id)AS i LEFT JOIN (SELECT id,name AS activity_name FROM tb_cash_activity)AS j ON i.cash_activity_id=j.id)AS k LEFT JOIN (SELECT id,mchid,name AS mchid_name FROM tb_channel)AS l ON k.channel_id=l.id)AS m LEFT JOIN (SELECT activitydata_id,business_no,is_white_table FROM tb_cash_activity_data_white_table)AS n ON m.id=n.activitydata_id)AS o LEFT JOIN (SELECT wyfMerchantID,`name` AS merchant_name,level_id AS merchant_level_id FROM tb_merchant)AS p ON o.business_no=p.wyfMerchantID)AS q LEFT JOIN (SELECT id,`name`AS merchant_level_name FROM tb_u_level)AS r ON q.merchant_level_id=r.id;
                '''
                cursor.execute(sql)
            except:
                sql = f'''
                SELECT q.*,r.merchant_level_name FROM (SELECT * FROM (SELECT * FROM (SELECT k.*,l.mchid,mchid_name FROM (SELECT i.*,j.activity_name FROM (SELECT g.*, h.account,branch_name,city_name,district_name,account_nine FROM (SELECT e.*, f.companyuser_account,companyuser_banch FROM (SELECT c.*,d.idcode,realname,openid FROM (SELECT a.*,b.companyuser_level_id,companyuser_mobile,companyuser_name FROM (SELECT id,cash_activity_id,amount,state,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%S')AS create_time,DATE_FORMAT(received_time,'%Y-%m-%d %H:%i:%S')AS received_time,DATE_FORMAT(expired_time,'%Y-%m-%d %H:%i:%S')AS expired_time,customer_user_id,companyuser_id,payment_no,return_msg,level_id,mobile,channel_id FROM tb_cash_activity_data WHERE id=1)AS a LEFT JOIN (SELECT id,nickname AS companyuser_name,mobile AS companyuser_mobile,level_id AS companyuser_level_id FROM tb_u_user)AS b ON a.companyuser_id=b.id)AS c LEFT JOIN (SELECT id,realname,idcode,new_openid AS openid FROM tb_u_customer_user)AS d ON c.customer_user_id=d.id)AS e LEFT JOIN (SELECT id,name AS companyuser_banch,account AS companyuser_account FROM tb_u_level)AS f ON e.companyuser_level_id=f.id)AS g LEFT JOIN (SELECT id,name AS branch_name,account,city_name,district_name,account_nine FROM tb_u_level)AS h ON g.level_id=h.id)AS i LEFT JOIN (SELECT id,name AS activity_name FROM tb_cash_activity)AS j ON i.cash_activity_id=j.id)AS k LEFT JOIN (SELECT id,mchid,name AS mchid_name FROM tb_channel)AS l ON k.channel_id=l.id)AS m LEFT JOIN (SELECT activitydata_id,business_no,is_white_table FROM tb_cash_activity_data_white_table)AS n ON m.id=n.activitydata_id)AS o LEFT JOIN (SELECT wyfMerchantID,`name` AS merchant_name,level_id AS merchant_level_id FROM tb_merchant)AS p ON o.business_no=p.wyfMerchantID)AS q LEFT JOIN (SELECT id,`name`AS merchant_level_name FROM tb_u_level)AS r ON q.merchant_level_id=r.id;
                '''
                cursor.execute(sql)
            ziduan = ['ID', '活动名称', '活动id', '所属市公司', '所属区县', '所属网点', '领取金额', '领取状态', '派发时间', '领取时间', '撤销时间', '用户openid',
                      '领取人姓名', '领取人手机号',
                      '领取人身份证', '派发员工', '派发员工手机号', '派发员工所属网点', '派发员工网点机构号', '领取渠道', '派发服务商号', '派发流水号', '失败原因', '机构号',
                      '微邮付商户号', '商户名称', '商户归属', '是否通过白名单参与']
            cols = ['id', 'activity_name', 'cash_activity_id', 'city_name', 'district_name', 'branch_name', 'amount',
                    'state', 'create_time', 'received_time', 'expired_time', 'openid', 'realname', 'mobile', 'idcode',
                    'companyuser_name', 'companyuser_mobile', 'companyuser_banch', 'companyuser_account', 'mchid_name',
                    'mchid', 'payment_no', 'return_msg', 'account_nine', 'business_no', 'merchant_name', 'merchant_level_name', 'is_white_table']
            response = StreamingHttpResponse(self.get_cashactivitydata_fromat(cols, cursor, conn, ziduan))
            response['Content-Type'] = 'application/octet-stream; charset=gbk'
            response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('微邮惠礼包派发数据.csv'))
            return response
        else:
            try:
                sql = f'''
                SELECT k.*,l.mchid,mchid_name FROM (SELECT i.*,j.activity_name FROM (SELECT g.*, h.account,branch_name,city_name,district_name,account_nine FROM (SELECT e.*, f.companyuser_account,companyuser_banch FROM (SELECT c.*,d.idcode,realname,openid FROM (SELECT a.*,b.companyuser_level_id,companyuser_mobile,companyuser_name FROM (SELECT id,cash_activity_id,amount,state,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%S')AS create_time,DATE_FORMAT(received_time,'%Y-%m-%d %H:%i:%S')AS received_time,DATE_FORMAT(expired_time,'%Y-%m-%d %H:%i:%S')AS expired_time,customer_user_id,companyuser_id,payment_no,return_msg,level_id,mobile,channel_id FROM tb_cash_activity_data {condition})AS a LEFT JOIN (SELECT id,nickname AS companyuser_name,mobile AS companyuser_mobile,level_id AS companyuser_level_id FROM tb_u_user)AS b ON a.companyuser_id=b.id)AS c LEFT JOIN (SELECT id,realname,idcode,new_openid AS openid FROM tb_u_customer_user)AS d ON c.customer_user_id=d.id)AS e LEFT JOIN (SELECT id,name AS companyuser_banch,account AS companyuser_account FROM tb_u_level)AS f ON e.companyuser_level_id=f.id)AS g LEFT JOIN (SELECT id,name AS branch_name,account,city_name,district_name,account_nine FROM tb_u_level)AS h ON g.level_id=h.id)AS i LEFT JOIN (SELECT id,name AS activity_name FROM tb_cash_activity)AS j ON i.cash_activity_id=j.id)AS k LEFT JOIN (SELECT id,mchid,name AS mchid_name FROM tb_channel)AS l ON k.channel_id=l.id;
                '''
                cursor.execute(sql)
            except:
                sql = f'''
                SELECT k.*,l.mchid,mchid_name FROM (SELECT i.*,j.activity_name FROM (SELECT g.*, h.account,branch_name,city_name,district_name,account_nine FROM (SELECT e.*, f.companyuser_account,companyuser_banch FROM (SELECT c.*,d.idcode,realname,openid FROM (SELECT a.*,b.companyuser_level_id,companyuser_mobile,companyuser_name FROM (SELECT id,cash_activity_id,amount,state,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%S')AS create_time,DATE_FORMAT(received_time,'%Y-%m-%d %H:%i:%S')AS received_time,DATE_FORMAT(expired_time,'%Y-%m-%d %H:%i:%S')AS expired_time,customer_user_id,companyuser_id,payment_no,return_msg,level_id,mobile,channel_id FROM tb_cash_activity_data WHERE id=1)AS a LEFT JOIN (SELECT id,nickname AS companyuser_name,mobile AS companyuser_mobile,level_id AS companyuser_level_id FROM tb_u_user)AS b ON a.companyuser_id=b.id)AS c LEFT JOIN (SELECT id,realname,idcode,new_openid AS openid FROM tb_u_customer_user)AS d ON c.customer_user_id=d.id)AS e LEFT JOIN (SELECT id,name AS companyuser_banch,account AS companyuser_account FROM tb_u_level)AS f ON e.companyuser_level_id=f.id)AS g LEFT JOIN (SELECT id,name AS branch_name,account,city_name,district_name,account_nine FROM tb_u_level)AS h ON g.level_id=h.id)AS i LEFT JOIN (SELECT id,name AS activity_name FROM tb_cash_activity)AS j ON i.cash_activity_id=j.id)AS k LEFT JOIN (SELECT id,mchid,name AS mchid_name FROM tb_channel)AS l ON k.channel_id=l.id;
                '''
                cursor.execute(sql)
            ziduan = ['ID', '活动名称', '活动id', '所属市公司', '所属区县', '所属网点', '领取金额', '领取状态', '派发时间', '领取时间', '撤销时间', '用户openid', '领取人姓名', '领取人手机号',
                      '领取人身份证', '派发员工', '派发员工手机号', '派发员工所属网点', '派发员工网点机构号', '领取渠道', '派发服务商号', '派发流水号', '失败原因', '机构号']
            cols = ['id', 'activity_name', 'cash_activity_id', 'city_name', 'district_name', 'branch_name', 'amount', 'state', 'create_time', 'received_time', 'expired_time', 'openid', 'realname', 'mobile', 'idcode',
                    'companyuser_name', 'companyuser_mobile', 'companyuser_banch', 'companyuser_account', 'mchid_name', 'mchid', 'payment_no', 'return_msg', 'account_nine']
            response = StreamingHttpResponse(self.get_cashactivitydata_fromat(cols, cursor, conn, ziduan))
            response['Content-Type'] = 'application/octet-stream; charset=gbk'
            response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('微邮惠礼包派发数据.csv'))
            return response

    def get_cashactivitydata_fromat(self, cols, cursor, conn, ziduan):
        tmp_str = ""
        # 返回文件的每一列列名
        for col in ziduan:
            tmp_str += '"%s",' % (col)
        yield tmp_str.strip(",") + "\n"
        STATE_ENUM = {
            1: '待领取',
            2: '已领取',
            3: '领取失败',
            4: '已撤销'
        }
        while True:
            tmp_str = ""
            row = cursor.fetchone()
            if row is None:
                cursor.close()
                conn.close()
                break
            for col in cols:
                if col == 'state':
                    tmp_str += '"%s",' % (STATE_ENUM[row[col]])
                elif col == 'is_white_table':
                    if row['is_white_table'] == 1:
                        tmp_str += '"%s",' % ('是')
                    else:
                        tmp_str += '"%s",' % ('否')
                elif col in ['idcode', 'payment_no']:
                    tmp_str += '"\'%s",' % (str(row[col]).encode('GBK', 'ignore').decode('gbk') if row[col] else '')
                elif col == 'expired_time':
                    tmp_str += '"%s",' % (str(row[col]).encode('GBK', 'ignore').decode('gbk') if row['state'] == 4 else '')
                # elif col == 'mchid_channel':
                #     if row['state'] in [2, 3]:
                #         if row['mchid'] == 'alipay':
                #             tmp_str += '"%s",' % '支付宝'
                #         else:
                #             tmp_str += '"%s",' % '微信'
                #     else:
                #         tmp_str += '"%s",' % ''
                elif col == 'mchid':
                    tmp_str += '"\'%s",' % (str(row[col]).encode('GBK', 'ignore').decode('gbk') if row[col] else '')
                else:
                    tmp_str += '"%s",' % (str(row[col]).encode('GBK', 'ignore').decode('gbk') if row[col] else '')
            yield tmp_str.strip(',') + "\n"

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        if instance.state != 1:
            return Response({'error': '当前派发记录不可撤销'}, status=status.HTTP_400_BAD_REQUEST)
        # if instance.companyuser_id != user.id:
        #     return Response({'error': '您无权限撤销该派发'}, status=status.HTTP_400_BAD_REQUEST)
        # activity_level = instance.cash_activity_level
        cash_activity_id = instance.cash_activity_id
        cash_activity_level_id = instance.cash_activity_level_id
        activity = instance.cash_activity
        amount = instance.amount
        if activity.activity_type == 8:
            return Response({'error': '当前派发记录不可撤销'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.activity_type in [1, 2, 3]:
            while True:
                activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                origin_take_amount = activity_level.take_amount
                origin_remain_amount = activity_level.remain_amount
                origin_p_take_amount = activity_level.p_take_amount
                origin_p_remain_amount = activity_level.p_remain_amount
                new_take_amount = origin_take_amount - amount
                new_remain_amount = origin_remain_amount + amount
                new_p_take_amount = origin_p_take_amount - amount
                new_p_remain_amount = origin_p_remain_amount + amount
                result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                          remain_amount=origin_remain_amount,
                                                          p_take_amount=origin_p_take_amount,
                                                          p_remain_amount=origin_p_remain_amount).update(
                    take_amount=new_take_amount, remain_amount=new_remain_amount, p_take_amount=new_p_take_amount,
                    p_remain_amount=new_p_remain_amount
                )
                if result == 0:
                    continue
                break
            while True:
                activity = CashActivity.objects.get(id=cash_activity_id)
                activity_origin_take_amount = activity.take_amount
                activity_origin_remain_amount = activity.remain_amount
                activity_new_take_amount = activity_origin_take_amount - amount
                activity_new_remain_amount = activity_origin_remain_amount + amount
                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                     remain_amount=activity_origin_remain_amount,
                                                     id=cash_activity_id).update(
                    take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                if result == 0:
                    continue
                break
            relation_set = activity_level.child_set.all()
            for relation in relation_set:
                parent = relation.parent
                parent.p_take_amount -= amount
                parent.p_remain_amount += amount
                parent.save()
            date_now = datetime.datetime.now()
            instance.state = 4
            instance.expired_time = date_now
            instance.save()
            try:
                cashactivitylevelrecord_data = {}
                cashactivitylevelrecord_data['activity_level_id'] = activity_level.id
                cashactivitylevelrecord_data['amount'] = amount
                cashactivitylevelrecord_data['operation_type'] = 6
                cashactivitylevelrecord_data['remain_amount'] = activity_level.remain_amount
                cashactivitylevelrecord_data['p_remain_amount'] = activity_level.p_remain_amount
                cashactivitylevelrecord_data['max_amount'] = activity_level.max_amount
                cashactivitylevelrecord_data['p_max_amount'] = activity_level.p_max_amount
                cashactivitylevelrecord_data['user_id'] = user.id
                cashactivitylevelrecord_data['remark'] = '管理员撤销派发二维码'
                cashactivitylevelrecord_data['activity_data_id'] = instance.id
                cashactivitylevelrecord_data['activity_id'] = activity.id
                CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                if instance.task_id:
                    celery_app.control.revoke(instance.task_id)
            except Exception as e:
                print(e)
                pass
        else:
            while True:
                activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                origin_take_amount = activity_level.take_amount
                origin_max_amount = activity_level.max_amount
                origin_p_take_amount = activity_level.p_take_amount
                origin_p_max_amount = activity_level.p_max_amount
                new_take_amount = origin_take_amount - amount
                new_max_amount = origin_max_amount - amount
                new_p_take_amount = origin_p_take_amount - amount
                new_p_max_amount = origin_p_max_amount - amount
                result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                          max_amount=origin_max_amount,
                                                          p_take_amount=origin_p_take_amount,
                                                          p_max_amount=origin_p_max_amount).update(
                    take_amount=new_take_amount, max_amount=new_max_amount, p_take_amount=new_p_take_amount,
                    p_max_amount=new_p_max_amount
                )
                if result == 0:
                    continue
                break
            while True:
                activity = CashActivity.objects.get(id=cash_activity_id)
                activity_origin_take_amount = activity.take_amount
                activity_origin_remain_amount = activity.remain_amount
                activity_new_take_amount = activity_origin_take_amount - amount
                activity_new_remain_amount = activity_origin_remain_amount + amount
                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                     remain_amount=activity_origin_remain_amount,
                                                     id=cash_activity_id).update(
                    take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                if result == 0:
                    continue
                break
            relation_set = activity_level.child_set.all()
            for relation in relation_set:
                parent = relation.parent
                parent.p_take_amount -= amount
                parent.p_max_amount -= amount
                parent.save()
            date_now = datetime.datetime.now()
            instance.state = 4
            instance.expired_time = date_now
            instance.save()
            try:
                cashactivitylevelrecord_data = {}
                cashactivitylevelrecord_data['activity_level_id'] = activity_level.id
                cashactivitylevelrecord_data['amount'] = amount
                cashactivitylevelrecord_data['operation_type'] = 6
                cashactivitylevelrecord_data['activity_type'] = 2
                cashactivitylevelrecord_data['remain_amount'] = activity.remain_amount
                cashactivitylevelrecord_data['p_remain_amount'] = activity.remain_amount
                cashactivitylevelrecord_data['max_amount'] = activity.max_amount
                cashactivitylevelrecord_data['p_max_amount'] = activity_level.p_max_amount
                cashactivitylevelrecord_data['user_id'] = user.id
                cashactivitylevelrecord_data['remark'] = '管理员撤销派发二维码'
                cashactivitylevelrecord_data['activity_data_id'] = instance.id
                cashactivitylevelrecord_data['activity_id'] = activity.id
                CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                if instance.task_id:
                    celery_app.control.revoke(instance.task_id)
            except Exception as e:
                print(e)
                pass
        try:
            if activity.activity_type in [2, 5]:
                cash_activity_rule = instance.cash_activity_rule
                cash_activity_rule.probability += 1
                cash_activity_rule.save()
        except:
            pass
        return Response({'success': '撤销成功'}, status=status.HTTP_200_OK)


class CashActivityDataKeguanModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_class = CashActivityDataKeguanFilter
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('cashactivitydata__payment_no', )

    def get_queryset(self):
        queryset = CashActivityDataKeguan.objects.all()
        return queryset.order_by('-id')

    def get_serializer_class(self):
        return CashActivityDataKeguanListModelSerializer


class CashActivityLevelRecordModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_class = CashActivityLevelRecordFilter
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('user__nickname', )
    serializer_class = CashActivityLevelRecordModelSerializer

    def get_queryset(self):
        return CashActivityLevelRecord.objects.all().order_by('-create_time')